package cn.elead.it.sso.server.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.gitee.elead.web.controller.SuperController;
import com.xkcoding.justauth.AuthRequestFactory;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;

/**
 * <p>
 * 第三方登录 Controller
 * </p>
 *
 * @package: com.xkcoding.oauth.controller
 * @description: 第三方登录 Controller
 * @author: luopeng
 * @date: Created in 2019-10-22 02:21
 * @copyright: Copyright (c) 2019
 * @version: V1.0
 * @modified: luopeng
 */
@Slf4j
@RestController
@RequestMapping("/oauth")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class JustAuthController extends SuperController {

	private final AuthRequestFactory factory;

	/**
	 * 登录类型
	 */
	@GetMapping
	public Map<String, String> loginType() {
		List<String> oauthList = factory.oauthList();
		return oauthList.stream().collect(Collectors.toMap(oauth -> oauth.toLowerCase() + "登录", oauth -> "http://oauth.xkcoding.com/demo/oauth/login/" + oauth.toLowerCase()));
	}

	/**
	 * 登录
	 *
	 * @param oauthType 第三方登录类型
	 * @param response  response
	 * @throws IOException
	 */
	@RequestMapping("/login/{oauthType}")
	public void renderAuth(@PathVariable String oauthType, HttpServletResponse response) throws IOException {
		AuthRequest authRequest = factory.get(oauthType);
		response.sendRedirect(authRequest.authorize(oauthType + "::" + AuthStateUtils.createState()));
	}

	/**
	 * 登录成功后的回调
	 *
	 * @param oauthType 第三方登录类型
	 * @param callback  携带返回的信息
	 * @return 登录成功后的信息
	 */
	@RequestMapping("/{oauthType}/callback")
	public AuthResponse<?> login(@PathVariable String oauthType, AuthCallback callback) {
		AuthRequest authRequest = factory.get(oauthType);
		AuthResponse<?> response = authRequest.login(callback);
		log.info("【response】= {}", JSONUtil.toJsonStr(response));
		return response;
	}
 
}